package com.cxf.windex.rest;

import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.msg.TableResultResponse;
import com.cxf.windex.base.rest.BaseController;
import com.cxf.windex.biz.WeiContentsBiz;
import com.cxf.windex.biz.WeiUserBiz;
import com.cxf.windex.entity.WeiContents;
import com.cxf.windex.entity.WeiLawyer;
import com.cxf.windex.entity.WeiUser;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @author chenxf
 * @date 3/8/2018
 * @description
 */
@Controller
@RequestMapping("content")
public class WeiContentController extends
    BaseController<WeiContentsBiz,WeiContents> {
  public static final Logger logger = LoggerFactory.getLogger(WeiContentController.class);

  /**
   * 文件存放 路径
   */
  @Value("${upload.path}")
  private String uploadPath;

  /**
   * 文件访问路径
   */
  @Value("${upload.url}")
  private String uploadUrl;


  @ApiOperation(value="新增/编辑", notes="新增编辑")
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse edit(WeiContents entity){
    if (entity.getId() == null || entity.getId() == 0) {
      return new ObjectRestResponse().rel(true).msg("文章ID不能为空");
    }
    entity = baseBiz.selectById(entity.getId());
    return new ObjectRestResponse().rel(true).msg("查询成功").result(entity);
  }

  @ApiOperation(value="查询文章列表", notes="查询文章列表")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "limit", value = "记录数", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "offset", value = "页码", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "orderStr", value = "排序 desc", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "title", value = "标题", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "layerName", value = "律师", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "expert", value = "专长", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "type", value = "类型", required = false, paramType = "query", dataType = "String")
  })
  @RequestMapping(value = "/list", method = RequestMethod.GET)
  @ResponseBody
  public TableResultResponse<WeiContents> list(
      @RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int offset,
      @RequestParam(defaultValue = "desc") String orderStr,String title,String layerName, String expert,String type) {
    Example example = new Example(WeiContents.class);
    Criteria criteria = example.createCriteria();
    if (StringUtils.isNotBlank(title)) {
      criteria.andLike("title", "%" + title + "%");
    }
    if (StringUtils.isNotBlank(layerName)) {
      criteria.andEqualTo("layerName", layerName );
    }
    if (StringUtils.isNotBlank(type)) {
      criteria.andLike("type", "%" + type + "%");
    }
    if (StringUtils.isNotBlank(expert)) {
      //String[] experts=expert.split(",");
      criteria.andLike("expert", "%" + expert + "%");
    }
    int count = baseBiz.selectCountByExample(example);
    PageHelper.startPage(offset, limit);
    PageHelper.orderBy("crt_time " + orderStr);

    return new TableResultResponse<WeiContents>(count,offset,limit,
        baseBiz.selectByExample(example));

  }

  @ApiOperation(value="保存", notes="保存")
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse save(WeiContents entity) {
    if(StringUtils.isNotBlank(entity.getContent()) &&
        entity.getContent().contains("img")){
      entity.setImage(getImg(entity.getContent()));
    }
    if (entity.getId() == null) {
      baseBiz.insertSelective(entity);
    } else {
      baseBiz.updateSelectiveById(entity);
    }

    return new ObjectRestResponse().rel(true).msg("保存成功");
  }

  @ApiOperation(value="上传图片", notes="上传图片")
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  @ResponseBody
  public Map upload(@RequestParam("file")MultipartFile file) {
    Map resultMap=new HashMap();
    if(file!=null){
      Map<String,String> savePcMap=saveFile(request,file,"article");
      if(savePcMap!=null){
        if(savePcMap.get("code").equals("0")){
          Map fileMap=new HashMap();
          fileMap.put("src",savePcMap.get("saveUrl"));
          resultMap.putAll(savePcMap);
          resultMap.put("data",fileMap);
          return resultMap;
        }else{
          return savePcMap;
        }
      }
    }
    return resultMap;
  }

  public String getImg(String content){
    Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
    Matcher m = p.matcher(content);
    if(m.find()){
      return m.group(1);
    }
    return "";
  }
}
